<?php
header("Content-type: text/html; charset=utf-8");
class wechatFun
{
    var $appid = "";
    var $appsecret = "";
	var $filePath = "";
	
	var $access_token = "";
	var $lasttime = 0;
    //构造函数，获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL, $accessJsonPath = NULL)
    {
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }
		if($accessJsonPath){
			$this->filePath = $accessJsonPath;
		}
		//$this->filePath .= 'zz_wechat/';
		$mytime = time();
		
        // 测试直接写入token到指定的日志中
//      $this->lasttime = 1395049256;
//      $this->access_token = "nRZvVpDU7LxcSi7GnG2LrUcmKbAECzRf0NyDBwKlng4nMPf88d34pkzdNcvhqm4clidLGAS18cN1RTSK60p49zIZY4aO13sF-eqsCs0xjlbad-lKVskk8T7gALQ5dIrgXbQQ_TAesSasjJ210vIqTQ";
//
//      if (time() > ($this->lasttime + 7200)){
//          $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
//          $res = $this->https_request($url);
//          $result = json_decode($res, true);
//          //save to Database or Memcache
//          $this->access_token = $result["access_token"];
//          $this->lasttime = time();
//      }
//		$this->logger($this->filePath."\n\n".$this->lasttime."\n\n".$this->access_token);
		
		// 不用缓存，直接获取token
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
		$res = $this->https_request($url);
		$result = json_decode($res, true);
		// print_r($result); exit;
		//save to Database or Memcache
		$this->access_token = $result["access_token"];
		$this->lasttime = $mytime;
		
		//3. 本地读取写入-------------------------------读取access_token
		/**
		$res = file_get_contents($this->filePath.'access_token.json');
		if($res==""){
			$this->lasttime = 0;
	        $this->access_token = "";
		}
		else{
			$result = json_decode($res, true);
	        $this->lasttime = $result["expires_time"];
	        $this->access_token = $result["access_token"];
		}
		
		//4. 写入本地token缓存-------------------------------写入access_token
        if ($mytime > ($this->lasttime + 3600)){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);
            //save to Database or Memcache
            $this->access_token = $result["access_token"];
            $this->lasttime = $mytime;
			//$this->logger("\n\n".'aaaaa'."\n\n".$res);
			file_put_contents($this->filePath.'access_token.json', '{"access_token": "'.$this->access_token.'", "expires_time": '.$this->lasttime.'}');
        
		}
		*/
    }
	
	//授权登陆 获取用户基本信息 开始--------------------------------------------------------------
	//生成扫码登录的URL
    public function qrconnect($redirect_url, $scope, $state = NULL)
    {
        //$url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->appid."&redirect_uri=".urlencode($redirect_url)."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".urlencode($redirect_url)."&response_type=code&scope=".$scope."&state=".$state."#wechat_redi";
        return $url;
    }
	//生成OAuth2的Access Token
    public function oauth2_access_token($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
	//刷新OAuth2的Access Token，一般不用
    public function oauth2_access_token_refresh($refresh_token)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
	//获取用户基本信息（OAuth2 授权的 Access Token 获取 未关注用户，Access Token为临时获取）
    public function oauth2_get_user_info($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
	//授权登陆 获取用户基本信息 结束--------------------------------------------------------------

	
    //获取关注者列表
    public function get_user_list($next_openid = NULL)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //获取用户基本信息
    public function get_user_info($openid)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
	
	//下载临时素材
    public function downLinMedia($mediaId)
    {
		//echo $this->access_token; exit;
		$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->access_token."&media_id=".$mediaId;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);    
		curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$package = curl_exec($ch);
		$httpinfo = curl_getinfo($ch);
		curl_close($ch);
		$imageAll = array_merge(array('header' => $httpinfo), array('body' => $package)); 
		return $package;
        //return json_decode($res, true);
    }
	
	protected function downloadWeixinFile($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);    
		curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$package = curl_exec($ch);
		$httpinfo = curl_getinfo($ch);
		curl_close($ch);
		$imageAll = array_merge(array('header' => $httpinfo), array('body' => $package)); 
		return $package;
	}

    //创建菜单
    public function create_menu($data)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
	//删除菜单
    public function delete_menu()
    {
		$url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->access_token;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
	//查询菜单
    public function select_menu()
    {
		echo $this->access_token;
		$url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->access_token;
        $res = $this->https_request($url);
		return json_decode($res, true);
    }

    //发送客服消息，已实现发送文本，其他类型可扩展
    public function send_custom_message($touser, $type, $data)
    {
        $msg = array('touser' =>$touser);
        switch($type)
        {
            case 'text':
                $msg['msgtype'] = 'text';
                $msg['text']    = array('content'=> urlencode($data));
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
        return $this->https_request($url, urldecode(json_encode($msg)));
    }

    //生成参数二维码
    public function create_qrcode($scene_type, $scene_id, $showGZUrl="arr")
    {
        switch($scene_type)
        {
            case 'QR_LIMIT_SCENE': //永久
                $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                break;
			case 'QR_LIMIT_SCENE22': //永久22
                $data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$scene_id.'"}}}';
                break;
            case 'QR_SCENE':       //临时
                $data = '{"expire_seconds": 36000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                break;
			case 'QR_SCENE22':       //临时
			    $data = '{"expire_seconds": 36000, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$scene_id.'"}}}';
			    break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        $result = json_decode($res, true);
		// print_r($result); exit;
		if($showGZUrl=="yes"){
			echo $result['url'];
		}
		
        //数据返回
		if($showGZUrl!="arr"){
        	return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result["ticket"]);
		}
		else{
			$mmArr['imgUrl'] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result["ticket"]);
			$mmArr['wxgzUrl'] = $result['url'];
			return $mmArr;
		}
    }
    
    //创建分组
    public function create_group($name)
    {
        $data = '{"group": {"name": "'.$name.'"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    
    //移动用户分组
    public function update_group($openid, $to_groupid)
    {
        $data = '{"openid":"'.$openid.'","to_groupid":'.$to_groupid.'}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    
    //上传多媒体文件
    public function upload_media($type, $file)
    {
        $data = array("media"  => "@".dirname(__FILE__).'\\'.$file);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }

    //https请求（支持GET和POST）
    protected function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
	
	protected function https_request22($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
	
	//日志记录
    protected function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 1000000;
            $log_filename = "wechatFunLog.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
}